﻿using System;
using TagLib;

namespace Mp3Tagger
{
	public class AudioFilesTools
	{

		static readonly string TEMP_FOLDER = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "Mp3Tagger");
		public AudioFilesTools()
		{
			if (!System.IO.Directory.Exists(TEMP_FOLDER))
			{
				System.IO.Directory.CreateDirectory(TEMP_FOLDER);
			}
			var files = System.IO.Directory.GetFiles(TEMP_FOLDER, "*.*");
			foreach (var filePath in files)
			{
				try
				{
					System.IO.File.Delete(filePath);
				}
				catch (Exception ex)
				{
					Console.WriteLine(ex);
				}
			}
		}


		public Tag ReadMp3Id3(string path)
		{
			try
			{
				var file = File.Create(path);
                return file.Tag;
			}
			catch (Exception ex)
			{ Console.WriteLine(ex.Message); return null; }
		}

		public void SaveImageToFile(string filePath, string imagePath)
		{
            var fileToSave = File.Create(filePath);
			try
			{
				if (fileToSave == null) return;
				if (fileToSave.Tag.Pictures.Length > 0)
					fileToSave.Tag.Pictures = null;
                var picture = new Picture(imagePath)
				                  {
				                      Type = PictureType.FrontCover,
				                      Description = ""
				                  };
				

			    fileToSave.Tag.Pictures = new IPicture[] { picture };
				fileToSave.Save();
			}
			catch (Exception ex)
			{ Console.WriteLine(ex.Message); }
		}

		public  string GetImageFromWeb(Uri address)
		{
            if (address == null) return null;
			try
			{
				var web = new System.Net.WebClient();
				if(!System.IO.Directory.Exists(TEMP_FOLDER))
				{
					System.IO.Directory.CreateDirectory(TEMP_FOLDER);
				}
				var filePath = System.IO.Path.Combine(TEMP_FOLDER,address.Segments[address.Segments.Length-1]);// @"D:\tmp\tempcover.jpg";
				if (System.IO.File.Exists(filePath)) return filePath;
				web.DownloadFile(address, filePath);
				if (System.IO.File.Exists(filePath))
				{
					return filePath;
				}
			}
			catch (Exception ex)
			{ Console.WriteLine(ex.Message); }
			return null;
		}
	}
}
